package es.decoroso.communicationAgent.bean;

import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * This encapsulates all the information relative to the message
 * 
 * @author Jesús W. Jiménez
 * 
 */
public class Message {

	int groupNumber;
	Vector2 orientation;
	Vector2 position;
	List<Rower> rowers = new LinkedList<Rower>();

	/**
	 * Constructor of the class
	 * 
	 * @param groupNumber
	 *            Group Number
	 * @param orientation
	 *            Orientation of the boat
	 * @param position
	 *            Position of the boat
	 * @param rowers
	 *            Rowers in the boat
	 */
	public Message(int groupNumber, Vector2 orientation, Vector2 position,
			List<Rower> rowers) {
		this.groupNumber = groupNumber;
		this.orientation = orientation;
		this.position = position;
		this.rowers = rowers;
	}

	/**
	 * Constructor of the class
	 * 
	 * Creates a message throught a json object
	 * 
	 * @param js
	 *            JSONObject with the information of the class
	 */
	public Message(JSONObject js) {
		try {
			this.groupNumber = js.getInt("groupNumber");
			this.orientation = new Vector2(js.getJSONObject("orientation"));
			this.position = new Vector2(js.getJSONObject("position"));
			this.rowers = getRowers(js.getJSONArray("rowers"));
		} catch (JSONException e) {
			System.out.println("Can not create Message from JSON");
			e.printStackTrace();
		}

	}

	/**
	 * Get the rowers list from a jsonarray
	 * 
	 * @param jsA
	 *            JSONArray with the rowers information
	 * @return List of rowers
	 */
	private List<Rower> getRowers(JSONArray jsA) {
		List<Rower> list = new LinkedList<Rower>();
		for (int i = 0; i < jsA.length(); i++) {
			try {
				list.add(new Rower(jsA.getJSONObject(i)));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return list;
	}

	/**
	 * Return the actual message parsed to json
	 * 
	 * @return JSONObject with the message information
	 */
	public JSONObject toJSON() {

		JSONArray ja = new JSONArray();

		for (Rower r : rowers) {
			ja.put(r.toJSON());
		}
		JSONObject js = new JSONObject();
		try {
			js.put("groupNumber", groupNumber);
			js.put("orientation", orientation.toJSON());
			js.put("position", position.toJSON());
			js.put("rowers", ja);
		} catch (JSONException ex) {
			Logger.getLogger(Message.class.getName()).log(Level.SEVERE, null,
					ex);
		}
		return js;
	}

}
